package com.geekcode.wol.controller;

import java.io.File;
import org.mapdb.DB;
import org.mapdb.DBMaker;
import org.mapdb.HTreeMap;
import org.mapdb.Serializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.geekcode.wol.model.Arp;
import com.geekcode.wol.util.Wol;

@RestController
@RequestMapping("/api/wol")
public class WolAPI extends BaseAPI{
	
	static DB database;
	static HTreeMap<String, Object> DATA;
	
	static {
		try {
			File file = new File("data/wol");
			file.getParentFile().mkdirs();
			try {
				init(file);
			} catch (Exception | Error e) {
				delFile(new File("data/wol"));
				init(file);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
	}
	
	static synchronized void init(File file) {
		database = DBMaker.newFileDB(file)
				.cacheDisable()
				.closeOnJvmShutdown()
				.make();
		DATA = database.createHashMap("DATA")
				.counterEnable()
				.keySerializer(Serializer.STRING)
				.valueSerializer(Serializer.JAVA)
				.makeOrGet();
	}
	
	static boolean delFile(File file) {
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        } else {
            File[] filenames = file.listFiles();
            for (File f : filenames) {
                delFile(f);
            }
            return file.delete();
        }
    }
	
	@GetMapping("/list")
	public Object arp() {
		return SUCCESS(DATA.values());
	}
	
	@PostMapping("/add")
	public Object add(@RequestBody Arp arp) {
		DATA.put(arp.getName().trim(), arp);
		database.commit();
		return SUCCESS();
	}
	
	@PostMapping("/del/{name}")
	public Object del(@PathVariable String name) {
		DATA.remove(name.trim());
		database.commit();
		return SUCCESS();
	}
	
	@PostMapping("/wake/{name}")
	public Object wake(@PathVariable String name) {
		Arp arp = (Arp) DATA.get(name.trim());
		return SUCCESS(Wol.wake(arp.getMac(), null));
	}
}
